/*
 * @Author: anonymous
 * @Date: 2022-01-22 14:17:28
 * @LastEditors: anonymous
 * @LastEditTime: 2022-04-18 11:41:15
 * @Description: webSocket
 */
import axios from 'axios'
var webSocket = null;

/**
 * @description: 提供socket连接方法
 * @param {*} path 连接地址：socket/[path]等
 * @return {*}
 * @Author: anonymous
 */
function conn_webSocket (path) {
  //判断用户当前浏览器是否支持websocket
  if ('WebSocket' in window) {
    let url = axios.defaults.baseURL;
    url = url.replace("http://", "");
    webSocket = new WebSocket(`ws://${url}/socket/${path}/${getSocketID()}`);
  } else {
    alert("浏览器不支持会话，请更换浏览器");
  }
  return webSocket;
}

/**
 * @description: 创建socket会话ID
 * @param {*}
 * @return {*}
 * @Author: anonymous
 */
function getSocketID () {
  let socketID = sessionStorage.getItem("socketID");
  if (socketID == null) {
    let sid = new Date().getTime();
    sessionStorage.setItem("socketID", sid);
    socketID = sid;
  }
  return socketID;
}


//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function () {
  if (webSocket != null) webSocket.close();
}

export default conn_webSocket;
